package com.zboot.comm.es.conf;

import com.zboot.comm.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
public class ElasticSearchRestClientConfig extends AbstractElasticsearchConfiguration {

    @Value("${spring.data.elasticsearch.enable}")
    boolean enableEs = true;
    @Value("${spring.data.elasticsearch.cluster-nodes}")
    String hosts;

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        if(!this.enableEs || StringUtils.isEmpty(this.hosts)){
            return null;
        }
        RestHighLevelClient client = null;
        try{
            String[] str = this.hosts.split(",");
            List<HttpHost> hosts = new ArrayList<>();
            for (String s : str) {
                s = s.trim();
                hosts.add(new HttpHost(StringUtils.substringBefore(s, ":"), Integer.valueOf(StringUtils.substringAfter(s, ":")), "http"));
            }
            client = new RestHighLevelClient(RestClient.builder(hosts.toArray(new HttpHost[hosts.size()])));
        }catch (Exception e){
            log.error(">>>> es连接失败：" + e.getMessage());
        }
        return client;
    }

}
